<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Factory\Mssql\AvsData AS FactoryAvsData;       //电厂数据模型
use App\Models\Local\AvsData AS LocalAvsData;   //总部数据模型
use Exception;
use Log;

/**
 * 从电厂获取地磅数据并保存到本地
 */
class AvsDataJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 180; //队列超时时间
    protected $date;
    protected $factory_conn; //电厂连接
    protected $local_conn; //本地连接
    protected $factory_data_table; //本地保存的原始数据集合
    protected $local_data_table; //本地保存的格式化后的数据集合
    public $tries = 3;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($params=null)
    {
        $this->date = $params && isset($params['date']) ? $params['date'] : '';
        $this->factory_conn = $params && isset($params['factory_conn']) ? $params['factory_conn'] : '';
        $this->local_conn = $params && isset($params['local_conn']) ? $params['local_conn'] : '';
        $this->factory_data_table = $params && isset($params['factory_data_table']) ? $params['factory_data_table'] : '';
        $this->local_data_table = $params && isset($params['local_data_table']) ? $params['local_data_table'] : '';
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->saveData();
    }

    protected function saveData(){
        try{
            $factoryAvsData = (new FactoryAvsData())->setConnection($this->factory_conn)->setTable($this->factory_data_table);  //连接电厂内部数据库
            $localAvsData = (new LocalAvsData())->setConnection($this->local_conn)->setTable($this->local_data_table);      //连接本地数据库表
        
            $latest_row = $localAvsData->findLatestReport();
            if($latest_row){
                $timestamp = strtotime($latest_row->TimeWeightingT);
            }
            else{
                $timestamp = strtotime("2024-01-01 00:00:00");
            }

            $rows = $factoryAvsData->select(['*'])
                ->where('TimeWeightingT', '>=',date("Y-m-d H:i:s", $timestamp))
                ->whereNotNull("WeightNet")
                ->orderBy("TimeWeightingT", "ASC")
                ->limit(1000)
                ->get();

            $params = [];
            if($rows && count($rows) > 0){
                foreach ($rows as $key => $item) {
                    $local_row = $localAvsData->findRowById($item->Id);
                    if(!$local_row){
                        //本地不存在则插入
                        $params[] = array(
                            'Id' => $item->Id,
                            'RecordNo' => $item->RecordNo,
                            'FlowNo'=> $item->FlowNo,
                            'Facility'=> $item->Facility,
                            'Source'=> $item->Source,
                            'Driver'=> $item->Driver,
                            'VehicleNo'=> $item->VehicleNo,
                            'VehicleType'=> $item->VehicleType,
                            'TransDept'=> $item->TransDept,
                            'ShiftType'=> $item->ShiftType,
                            'ComputerName'=> $item->ComputerName,
                            'WeightChecker'=> $item->WeightChecker,
                            'InstrumentNo'=> $item->InstrumentNo,
                            'ImportStatus'=> $item->ImportStatus,
                            'WeightGross'=> $item->WeightGross,
                            'WeightTare'=> $item->WeightTare,
                            'WeightNet'=> $item->WeightNet,
                            'WeightDeduction'=> $item->WeightDeduction,
                            'BillingUnit'=> $item->BillingUnit,
                            'BillingTotal'=> $item->BillingTotal,
                            'TimeLoading'=> $item->TimeLoading,
                            'TimeWeightingG'=> $item->TimeWeightingG,
                            'TimeWeightingT'=> $item->TimeWeightingT,
                            'TimeWeightingN'=> $item->TimeWeightingN,
                            'Memo'=> $item->Memo,
                            'RecordStatus'=> $item->RecordStatus,
                            'RecordCreatedTime'=> $item->RecordCreatedTime,
                            'RecordCreatorId'=> $item->RecordCreatorId,
                            'FieldNo'=> $item->FieldNo,
                            'InputType'=> $item->InputType,
                            'GarbageType'=> $item->GarbageType,
                            'RecordVersion'=> $item->RecordVersion,
                            'VehicleDoorNo'=> $item->VehicleDoorNo,
                            'DepartmentSTA'=> $item->DepartmentSTA,
                            'TimePhoto'=> $item->TimePhoto,
                            'RfidTag'=> $item->RfidTag,
                            'Region'=> $item->Region,
                            'flag'=> 0
                        );
                    }
                }
            }

            if($params && count($params) > 0){
                foreach($params as $item){
                    $Id = $item['Id'];
                    unset($item['Id']);
                    $localAvsData->updateOrCreate([
                        "Id" => $Id
                    ], $item);
                }
                //$localAvsData->insertMany($params);
                Log::info($this->date . '地磅数据库数据插入本地成功'.count($params).'条');
            }
            else{
                Log::info($this->date . '地磅数据库没有数据插入');
            }
        }
        catch(Exception $ex){
            Log::info('连接电厂地磅数据库异常');
            Log::info(var_export($ex->getMessage(), true));
            $this->fail();
        }
    }
}
